 <template>
  <div class="page-order">
    <el-row>
      <el-col :offset="2" :span="6" class="navbar">
          <el-row style="text-align:center;">
            <img :src="'data:image/png;base64,'+user.headImg" alt="头像" width="200px" height="200px" />
            <!-- <el-image style="width: 100px; height: 100px" src="api/user/image/get/1.jpg"></el-image> -->
          </el-row>
          <el-divider></el-divider>
          <el-row>
            <el-col :span="12">
              <el-button icon="el-icon-edit" @click="editPwd = true">修改密码</el-button>
            </el-col>
            <el-col :span="12">
              <el-button icon="el-icon-user" @click="editInfo = true">修改信息</el-button>
            </el-col>
          </el-row>
      </el-col>
      <el-col :offset="1" :span="12" class="table">
          <el-row style="height:90px">
            <el-tag
              effect="light"
              type="danger"
              style="margin-left:20px;width:70px;height:40px;font-size:15px;text-align:center;"
            >账号</el-tag>
            <el-tag
              effect="plain"
              style="margin-left:10px;width:300px;height:40px;font-size:15px;text-align:center;"
            >{{user.username}}</el-tag>
          </el-row>
          <el-row style="height:90px">
            <el-tag
              effect="light"
              type="danger"
              style="margin-left:20px;width:70px;height:40px;font-size:15px;text-align:center;"
            >昵称</el-tag>
            <el-tag
              effect="plain"
              style="margin-left:10px;width:300px;height:40px;font-size:15px;text-align:center;"
            >{{user.name}}</el-tag>
          </el-row>
          <el-row style="height:90px">
            <el-tag
              effect="light"
              type="danger"
              style="margin-left:20px;width:70px;height:40px;font-size:15px;text-align:center;"
            >地址</el-tag>
            <el-tag
              effect="plain"
              style="margin-left:10px;width:300px;height:40px;font-size:15px;text-align:center;"
            >{{user.address}}</el-tag>
          </el-row>
          <el-row style="height:90px">
            <el-tag
              effect="light"
              type="danger"
              style="margin-left:20px;width:80px;height:40px;font-size:15px;text-align:center;"
            >联系方式</el-tag>
            <el-tag
              effect="plain"
              style="margin-left:10px;width:300px;height:40px;font-size:15px;text-align:center;"
            >{{user.telephone}}</el-tag>
          </el-row>
      </el-col>
    </el-row>

    <el-dialog title="修改密码" :visible.sync="editPwd" width="40%" center>
      <el-form :model="form" :rules="rules" ref="form" label-width="100px" class="demo-ruleForm">
        <el-form-item label="原密码" prop="oldPwd">
          <el-input v-model="form.oldPwd"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPwd">
          <el-input v-model="form.newPwd"></el-input>
        </el-form-item>
        <el-form-item label="重复新密码" prop="rePwd">
          <el-input v-model="form.rePwd"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editPwd = false,$refs['form'].resetFields();">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="修改信息" :visible.sync="editInfo" width="40%" center>
      <el-form :model="user" :rules="userRule" ref="user" label-width="100px" class="demo-ruleForm">
        <el-form-item label="昵称" prop="name">
          <el-input v-model="user.name"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="user.address"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="telephone">
          <el-input v-model="user.telephone"></el-input>
        </el-form-item>
        <el-form-item label="新头像" prop="headImg">
          <el-upload
            class="avatar-uploader"
            action="api/user/upload/img"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <el-image v-if="imgUrl" :src="imgUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editInfo = false,$refs['user'].resetFields();">取 消</el-button>
        <el-button @click="editUser('user')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import * as homeApi from "@/server/home.js";
import { isvalidPass } from "@/assets/js/validate.js";
export default {
  layout: "product",
  data() {
    var checkPwd = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form.newPwd) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (!isvalidPass(value)) {
        callback(
          new Error("密码以字母开头 长度在6~15之间 只能包含字母、数字和下划线")
        );
      } else {
        if (this.form.rePwd !== "") {
          this.$refs.form.validateField("rePwd");
        }
        callback();
      }
    };
    return {
      editPwd: false,
      editInfo: false,
      flag: false,
      imgUrl: "",
      form: {
        oldPwd: "",
        newPwd: "",
        rePwd: ""
      },
      user: {
        headImg: "",
        user: "",
        username: "",
        address: "",
        telephone: "",
        img: ""
      },
      rules: {
        oldPwd: [{ required: true, message: "请输入原密码", trigger: "blur" }],
        newPwd: [{ required: true, validator: validatePass, trigger: "blur" }],
        rePwd: [{ required: true, validator: checkPwd, trigger: "blur" }]
      },
      userRule: {
        telephone: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            validator: function(rule, value, callback) {
              if (/^1[34578]\d{9}$/.test(value) == false) {
                callback(new Error("请输入正确的手机号"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ]
      }
    };
  },
  methods: {
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          homeApi
            .updatePwd(this.user.userId, this.user.username, this.form)
            .then(res => {
              if (res.data.code == 200) {
                this.$message({
                  type: "success",
                  message: "修改成功！请重新登录"
                });
                this.logout();
              } else {
                this.$message({
                  type: "error",
                  message: res.data.message
                });
              }
            });
        } else {
          return false;
        }
      });
    },
    editUser: function() {
      this.$refs["user"].validate(valid => {
        if (valid) {
          homeApi.updateUser(this.user).then(res => {
            if (res.data.code == 200) {
              this.$message({
                type: "success",
                message: "修改成功!"
              });
              this.editInfo = false;
              location.reload();
            } else {
              this.$message({
                type: "error",
                message: res.data.message
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    logout: function() {
      homeApi.logout(this.user.userId).then(res => {
        if (res.data.code == 200) {
          this.$router.push({ path: "/login" });
        }
      });
    },
    getUser: function() {
      homeApi.getUser(3).then(result => {
        console.log(result);
        this.user = result.data.data;
      });
    },
    handleAvatarSuccess(res, file) {
      console.log(res);
      if (res == "null") {
        this.$message({
          type: "error",
          message: "上传失败!"
        });
        return;
      }
      this.imgUrl = "/api/user/image/get/" + res;
      this.user.img = res;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    }
  },
  created() {
    this.getUser();
  }
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
